package com.tgjorgoski.spellcheck.highlight;

import java.awt.*;
import java.util.*;
import java.util.List;

import javax.swing.text.Document;
import javax.swing.text.Highlighter.*;

import com.swabunga.spell.event.*;
import com.tgjorgoski.spellcheck.*;

/**
 * 
 * 
 * @author Tanasije Gjorgoski <tgjorgoski@novizio.com>
 */
public class SpellcheckHighlighter extends NodesHighlighter implements SpellCheckListener, DictionaryChangeListener {

	// An instance of the private subclass of the default highlight painter
	private HighlightPainter myHighlightPainter 
			= new HLPainterUnderlineZigZag(Color.RED, 3, -1);
	private SpellChecker spellCheck;
	private WordTokenizer docTokenizer;
	private List<NodeSection> nodeSections=new Vector<NodeSection>();

	public SpellcheckHighlighter() {
		spellCheck = SpellcheckDictionaries.constructSpellChecker();
		if (spellCheck==null) return;
		spellCheck.addSpellCheckListener(this);
		SpellcheckDictionaries.addDictionaryChangesListener(this);
	}
	/**
	 * @param mw
	 * @param text
	 * @return
	 * 
	 * @see europa.client.sdoc.view.editorsEnrich.NodesHighlighter#getNodeSectionsIterator(europa.client.sdoc.model.ModelWrapper, java.lang.String)
	 */
	public NodeSectionsIterator getNodeSectionsIterator(Document doc) {
		//docTokenizer = new FixedDocumentWordTokenizer(doc);
		docTokenizer = new DocumentWordTokenizer(doc);
		nodeSections.clear();
		spellCheck.checkSpelling(docTokenizer);
		return NodeSectionsIterator.wrap(nodeSections.iterator());
	}
	/**
	 * @return
	 * 
	 * @see europa.client.sdoc.view.editorsEnrich.NodesHighlighter#getHighlighterPainter()
	 */
	public HighlightPainter getHighlighterPainter() {
		return myHighlightPainter;
	}
	
	/**
	 * @param event
	 * 
	 * @see com.swabunga.spell.event.SpellCheckListener#spellingError(com.swabunga.spell.event.SpellCheckEvent)
	 */
	public void spellingError(SpellCheckEvent event) {
	    //first check if maybe word is not to be handled as incorrect (e.g. ignored)
	    if (SpellcheckDictionaries.isCorrect(event.getInvalidWord())) {
	        event.ignoreWord(false);
	        return;
	    }
		int start = event.getWordContextPosition();
		int end = start + event.getInvalidWord().length();
		nodeSections.add(new NodeSection(start, end));
	}

	public void userDictionaryModified() {
	    fireHighlightChangeListeners();
    }
    public void mainDictionaryChanged() {
        fireHighlightChangeListeners();
    }
    public void userDictionaryChanged() {
        fireHighlightChangeListeners();
    }
}
